const express = require('express');
const router = express.Router();
const { body, param, query, validationResult } = require('express-validator');
const Product = require('../models/Product');
const Translation = require('../models/Translation');
const logger = require('../utils/logger');

const validate = (req, res, next) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ success: false, errors: errors.array() });
  }
  next();
};

// 获取产品列表
router.get('/', async (req, res, next) => {
  try {
    const products = await Product.find({ enabled: true })
      .sort({ createdAt: -1 });
    
    res.json({
      success: true,
      data: products
    });
  } catch (error) {
    next(error);
  }
});

// 获取产品的所有词条 (用于产品集成)
router.get('/:productCode/translations',
  [
    param('productCode').notEmpty(),
    query('locale').notEmpty().withMessage('locale参数必填'),
    query('namespace').optional(),
    query('version').optional(), // 指定版本，不指定则获取最新已发布的
  ],
  validate,
  async (req, res, next) => {
    try {
      const { productCode } = req.params;
      const { locale, namespace, version } = req.query;
      
      // 查找产品
      const product = await Product.findOne({ code: productCode.toUpperCase() });
      if (!product) {
        return res.status(404).json({ success: false, message: '产品不存在' });
      }
      
      // 构建查询条件
      const filter = {
        productId: product._id,
        deleted: false
      };
      
      if (namespace) filter.namespace = namespace;
      
      // 如果指定版本，需要从Release中查找该版本的词条
      // 这里简化处理，实际应该从Release关联的词条ID查询
      if (version) {
        // TODO: 从Release中获取指定版本的词条
      } else {
        // 获取已发布的最新词条
        filter.status = 'published';
      }
      
      const translations = await Translation.find(filter).lean();
      
      // 构建多语言JSON对象
      const messages = {};
      translations.forEach(t => {
        // 处理 locales Map 结构
        let locales = t.locales;
        if (locales instanceof Map) {
          locales = Object.fromEntries(locales);
        } else if (!locales || typeof locales !== 'object') {
          locales = {};
        }
        
        const key = namespace ? `${t.namespace}.${t.key}` : t.key;
        const value = locales[locale] || locales[product.defaultLocale] || '';
        
        // 支持嵌套键 (如: nav.home -> { nav: { home: '...' } })
        const keys = key.split('.');
        let current = messages;
        for (let i = 0; i < keys.length - 1; i++) {
          if (!current[keys[i]]) current[keys[i]] = {};
          current = current[keys[i]];
        }
        current[keys[keys.length - 1]] = value;
      });
      
      res.json({
        success: true,
        data: messages,
        meta: {
          product: product.name,
          locale,
          namespace: namespace || 'all',
          count: translations.length
        }
      });
    } catch (error) {
      next(error);
    }
  }
);

module.exports = router;
